package com.zahb.qadx;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.cretin.www.cretinautoupdatelibrary.model.DownloadInfo;
import com.cretin.www.cretinautoupdatelibrary.utils.AppUpdateUtils;
import com.google.gson.Gson;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.Upgrade;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.TaskListActivity;
import com.zahb.qadx.ui.fragment.HomeFragment;
import com.zahb.qadx.ui.fragment.MineFragment;
import com.zahb.qadx.ui.fragment.TaskFragment;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainActivity extends BaseActivity {
    private HomeFragment homeFragment;
    private TaskFragment taskFragment;
    private MineFragment mineFragment;
    private FragmentManager manager;
    private RadioButton rbHome, rbTask, rbMine;
    List<Fragment> fragmentList = new ArrayList<>();
    List<RadioButton> radioButtonList = new ArrayList<>();
    private int prePosition = 0;
    private int mPagePosition = -1;
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    @SuppressLint("StaticFieldLeak")
    public static MainActivity sMainActivity;
    private static final String[] sStoragePermissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
    ,Manifest.permission.CAMERA};
     private ImageView start_the_figure;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sMainActivity = this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), sStoragePermissions, 0x101);
            }
        }
        pref = getSharedPreferences("version",MODE_PRIVATE);
        editor = pref.edit();
        //APP升级
        // TODO: 2021/5/12  暂时注掉 升级 
        upgrade();
    }

    private void upgrade() {
        Map<String, Object> params = new HashMap<>();
        params.put("clientSystem", "2");
        Gson mGson = new Gson();
        String json = mGson.toJson(params);
        Log.e("json",json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getUpgrade(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (response.getData()!=null){
                            Upgrade update=response.getData();
                            //更新
                            update(update.getVersionCode(),update.getUpdateLog(),update.getVersionName(),update.getDownurl(),update.getIsForceUpdate());
                        }

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
//                    Tips.RequestError(getActivity());

                }));

    }
    /*
    downurl:下载地址
    versionCode:最新版本133
    isForceUpdate:1强制 0随意
    versionName:文字版本号v1.1.0
    updateLog:优化文案
     */
    private  void  update(int versionCode ,String updateLog, String versionName,String downurl,int isForceUpdate){
        int   versionCode_new = pref.getInt("versionCode",0);
        if (versionCode==versionCode_new&&isForceUpdate==0){
            return;
        }else {
            editor.putInt("versionCode",versionCode);
            editor.commit();
        }

//        第二种方式，使用MODEL方式，组装好对应的MODEL，传入sdk中
        DownloadInfo info = new DownloadInfo().setApkUrl(downurl)
                .setProdVersionCode(versionCode)
                .setProdVersionName(versionName)
                .setMd5Check("68919BF998C29DA3F5BD2C0346281AC0")
                .setForceUpdateFlag(isForceUpdate)
                .setUpdateLog(updateLog);
                 AppUpdateUtils.getInstance()
//                .addMd5CheckListener(...)//添加MD5检查更新
//                        .addAppDownloadListener(...)//添加文件下载监听
                .checkUpdate(info);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int type =  intent.getIntExtra("type",0);
        if(type==1){
            if(mineFragment!=null){
                mineFragment.archives();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sMainActivity = null;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        initView();
        initOnClickListener();
        getTaskData();
    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    private void initView() {
//        start_the_figure=findViewById(R.id.start_the_figure);
        rbHome = findViewById(R.id.rb_home);
        rbTask = findViewById(R.id.rb_task);
        rbMine = findViewById(R.id.rb_mine);
        homeFragment = new HomeFragment();
        taskFragment = new TaskFragment();
        mineFragment = new MineFragment();
        //添加fragment集合
        fragmentList.add(homeFragment);
        fragmentList.add(taskFragment);
        fragmentList.add(mineFragment);
        //添加radioButton集合
        radioButtonList.add(rbHome);
        radioButtonList.add(rbTask);
        radioButtonList.add(rbMine);
        manager = getSupportFragmentManager();
        manager.beginTransaction().add(R.id.content_home, homeFragment).show(homeFragment).commitAllowingStateLoss();
        radioButtonList.get(0).setChecked(true);
        radioButtonList.get(0).setSelected(true);
//        Thread myThread = new Thread() {//创建子线程
//            @Override
//            public void run() {
//                try {
//                    sleep(2000);//使程序休眠一秒
//                    start_the_figure.setVisibility(View.GONE);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        myThread.start();//启动线程
    }

    private void initOnClickListener() {
        radioButtonList.get(0).setOnClickListener(v -> {
            hideAndShow(0);
            radioButtonList.get(0).setSelected(true);
            radioButtonList.get(1).setSelected(false);
            radioButtonList.get(2).setSelected(false);
        });
        radioButtonList.get(1).setOnClickListener(v -> {
            hideAndShow(1);
            radioButtonList.get(0).setSelected(false);
            radioButtonList.get(1).setSelected(true);
            radioButtonList.get(2).setSelected(false);
        });
        radioButtonList.get(2).setOnClickListener(v -> {
            hideAndShow(2);
            radioButtonList.get(0).setSelected(false);
            radioButtonList.get(1).setSelected(false);
            radioButtonList.get(2).setSelected(true);
        });
    }

    private void hideAndShow(int position) {
        if (mPagePosition == position) {
            // 已经在当前页了
            return;
        }
        mPagePosition = position;
        FragmentTransaction transaction = manager.beginTransaction();
        if (fragmentList.get(position).isAdded()) {
            transaction.hide(fragmentList.get(prePosition)).show(fragmentList.get(position)).commit();

        } else {
            transaction.add(R.id.content_home, fragmentList.get(position))
                    .hide(fragmentList.get(prePosition))
                    .show(fragmentList.get(position)).commitAllowingStateLoss();
//            commitAllowingStateLoss()
            // TODO: 2021/4/6   再出现崩就调用commitAllowingStateLoss()替换commit()

        }
        //点击后字体变颜色
//        radioButtonList.get(prePosition).setTextColor(Color.GRAY);
        prePosition = position;
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                showToast("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    AlertDialog alertDialog;

    private void showTaskDialog() {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(getContext());
        alertDialog = customizeDialog.create();
        View dialogView = View.inflate(this, R.layout.dialog_learn, null);
        alertDialog.setCancelable(false);
        TextView tv_Learning = dialogView.findViewById(R.id.tv_Learning);
        ImageView img_back = dialogView.findViewById(R.id.img_return);
        img_back.setOnClickListener(v -> alertDialog.dismiss());
        tv_Learning.setOnClickListener(v -> {
            TaskListActivity.actionStart(this);
            alertDialog.dismiss();
        });
        alertDialog.setView(dialogView);
        alertDialog.show();
    }

    private void isTodayFirstShow() {
        SharedPreferences pref = getSharedPreferences("dialogLog", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        int id = BaseApplication.getContext().getDataLogin().getUser().getId();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String lastTime = pref.getString("date_" + id, "");
        try {
            String currentTime = dateFormat.format(new Date());
            if (!TextUtils.equals(lastTime, currentTime)) {
                showTaskDialog();
                editor.putString("date_" + id, currentTime).apply();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getTaskData() {
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            addDisposable(RetrofitService.getNetService()
                    .getTaskList(1, 2, 1)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                            if (response.getData().getTotal() > 0) {
                                isTodayFirstShow();
                            }
                        }
                    }, Throwable::printStackTrace));
        }
    }
}